package com.tuniondata.netty.bean;

import com.tuniondata.netty.common.protocol.Protocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author yuxinchao
 */
public class MessageEncoder extends MessageToByteEncoder {

    private static final Logger log = LoggerFactory.getLogger(MessageEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        RpcMessage rpcMessage = (RpcMessage) msg;
        byte[] data = rpcMessage.toByteArray();

        log.info("encode len:{}, data:{}", data.length, new String(data));

        out.writeInt(data.length);
        out.writeBytes(data);
    }
}
